package com.hp.interceptor;

import com.hp.annotation.CheckRepeatSubmit;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * @author hp
 */
@Slf4j
@Aspect
@Component
public class CheckRepeatSubmitInterceptor {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Before("@annotation(com.hp.annotation.CheckRepeatSubmit)")
    public void beforeIntercept(JoinPoint point) throws Exception {
        System.out.println("beforeIntercept");
        /**获取当前方法信息*/
        Method method = ((MethodSignature) point.getSignature()).getMethod();
        /**获取注解*/
        CheckRepeatSubmit checkRepeatSubmit = method.getAnnotation(CheckRepeatSubmit.class);
        /**获取信息生成指定的key*/
        String key = generateKey(point);
        /**校验key*/
        Boolean isOk = handleKey(key, checkRepeatSubmit);
        /**校验是否合法*/
        if (!isOk) {
            log.info("重复请求");
            throw new Exception("重复请求");
        }
    }

    private Boolean handleKey(String key, CheckRepeatSubmit checkRepeatSubmit) {
        return redisTemplate.opsForValue().setIfAbsent(key, "0", checkRepeatSubmit.expires(), TimeUnit.SECONDS);
    }

    /**
     * 生成key
     */
    public String generateKey(JoinPoint point) {

        String targetName = point.getTarget().getClass().getName();
        String methodName = point.getSignature().getName();
        String arguments = point.getArgs().toString();
        /**生成key*/
        String key = targetName + methodName;// + arguments
        return key;
    }

}
